#include <pthread.h>
#include <iostream>
#include <unistd.h>
#include "mylock.h"

volatile int tickets = 1000;//总票数
My_mutex mutex;//for Geet_tickets
//My_mutex mutex_print;
bool Get_tickets()
{
  bool flag = false;
  Mutex_Guard mylock(&mutex);
  if(tickets > 0)
  {
    tickets--;

    std::cout << "thread: " << pthread_self() << " success " << "tickets: " << tickets << std::endl;
    flag = true;
  }
  return flag;
}//Get_tickets

void* thread_op(void *arge)
{
  while(true)
  {

    //Mutex_Guard mylock(&mutex_print);
    if(Get_tickets())
    {
      usleep(1000);
      //std::cout << (char*)arge << " success " << "tickets: " << tickets << std::endl;
    }
    else 
    {
      std::cout << (char*)arge << " fail " << "tickets: " << tickets << std::endl;
      break;
    }
  }

  return (void*)(0);
}//thread_op

int main()
{
  pthread_t t1, t2, t3;

  pthread_create(&t1, NULL, thread_op, (void*)"thread 1");
  pthread_create(&t2, NULL, thread_op, (void*)"thread 2");
  pthread_create(&t3, NULL, thread_op, (void*)"thread 3");

  pthread_join(t1, NULL);
  pthread_join(t2, NULL);
  pthread_join(t3, NULL);
  
  return 0;
}
